package com.yuyou.tas.feedback.service.impl;

import com.yuyou.tas.feedback.IWeixinFIleService;
import com.yuyou.tas.feedback.service.ICallableService;
import com.yuyou.tas.util.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.*;

@Service
public class CallableServiceImpl implements ICallableService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IWeixinFIleService weixinFIleService;

    /**
     * 使用completionService将微信图片下载并上传至七牛云
     * 返回七牛云地址数组
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public String[] completionServiceCount(String[] url_Array , String type) throws Exception{
        ExecutorService executorService = Executors.newCachedThreadPool();
        String[] urls = new String[url_Array.length];
        CompletionService<String> completionService = new ExecutorCompletionService<>(
                executorService);
        for (int i = 0; i < url_Array.length; i++) {
            completionService.submit(getTask(i , url_Array[i] , type));
        }

        for(int i=0;i<url_Array.length;i++){
            String temp = completionService.take().get();
            if(StringUtils.isEmpty(temp)){
                throw new BusinessException("微信文件处理异常，线程返回空字符串");
            }
            urls[i] = temp;
        }

        executorService.shutdown();
        return urls;
    }

    private Callable<String> getTask(final int no , final String id , final String type) {
        Callable<String> task = () -> {
            String url = weixinFIleService.upload2Qiniu(id , type);
            logger.info("thread:"+no+" 处理微信"+type+"类型文件下载并上传至七牛云id："+id);
            return url;
        };
        return task;
    }

}
